#include "keyboard.h"

#define lines 2

/* you need edit this code, port to your project */
#define KEYPORT P1

#ifdef __SDCC

#if lines == 2
#define line0 P1_0
#define line1 P1_1
#elif lines == 4
#define line0 P1_0
#define line1 P1_1
#define line2 P1_2
#define line3 P1_3
#endif

#else // Keil C51

#if lines == 2
sbit line0 = P1^0;
sbit line1 = P1^1;
#elif lines == 4
sbit line0 = P1^0;
sbit line1 = P1^1;
sbit line2 = P1^2;
sbit line3 = P1^3;
#endif

#endif

#if lines == 2
#define KEYPORT_V 0x03
#define SCANCODE  0x0b
#elif lines == 4
#define KEYPORT_V 0x0f
#define SCANCODE  0xef;
#endif

/* check key input */
bit iskeyinput(void)
{
    KEYPORT = KEYPORT_V; //0000 0011 low two bit set 1, high two bit set 0
    if((KEYPORT & KEYPORT_V) == KEYPORT_V)
        return 0; // no key is colsed.
    else
        return 1;
}

void wait_key_release(void)
{
    while(1)
    {
        KEYPORT = KEYPORT_V;
        if((KEYPORT & KEYPORT_V) == KEYPORT_V) break; // no key is colsed.
    }
}

uchar key_identify(void)
{
    uchar linecode = 0, rowcode = 0;
    uchar i;
    uchar scancode = SCANCODE; // 0000 1011 initial scancode, and set column 1 as 0, other is 1

    for(i =0; i < lines; i ++)
    {
        KEYPORT = scancode;
        if((KEYPORT & KEYPORT_V) == KEYPORT_V) // only check row line
        {
            rowcode ++;
            scancode = scancode <<1 | 1;
        }
        else
        {
            if(line0 == 0) linecode = 0;
            #if lines == 2
            if(line1 == 0) linecode = 2;
            #elif lines == 4
            if(line1 == 0) linecode = 4;
            if(line2 == 0) linecode = 8;
            if(line3 == 0) linecode = 12;
            #endif
            break;

        }
    }
    return linecode + rowcode;
}

